<?php
declare (strict_types=1);

namespace app\course\service\agent\admin;

use app\common\logic\category\admin\Category;
use app\common\service\BaseService;
use app\course\logic\agent\admin\CourseAgent as AgentLogic;
use app\course\logic\base\Course;
use app\course\logic\classes\admin\Classes as ClassesLogic;
use app\course\logic\live\admin\Live as LiveLogic;
use app\course\logic\live\admin\LiveSmall as LiveSmallLogic;
use app\course\logic\video\admin\Video as VideoLogic;
use app\school\logic\school\admin\School as SchoolLogic;
use app\course\logic\base\admin\CourseStudent;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageForm;
use eduline\admin\page\PageList;
use think\annotation\Inject;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;

/**
 * 点播课程接口类-后台
 */
class Agent extends BaseService
{

    /**
     * @Inject()
     *
     * @var AgentLogic
     */
    protected $agentLogic;

    /**
     * 代理记录
     *
     * @return mixed
     */
    public function index()
    {
        $mhmId = Request::get('mhm_id/d', request()->mhm_id);
        // 搜索功能
        $map = [];
        $mhmId && $map[] = ['mhm_id', '=', $mhmId];
        Request::has('title', 'get', true) && $map[] = ['title', 'like', '%' . Request::get('title/s') . '%'];
        $category = Request::get('category/d', 0);
        $category && $map[] = ['category', 'like', '%,' . $category . ',%'];

        $data = $this->agentLogic->getList($map);
        // 定义字段
        $keyList = [
            'title'            => ListItem::make('custom')->title('名称')->width(140),
            'course_type_text' => ListItem::make()->title('课程类型'),
            'cates'            => ListItem::make('custom')->title('分类')->width(142),
            'price'            => ListItem::make('custom')->title('平台价')->width(40)
        ];

        // 课程分类
        $category = app(Category::class)->cascaderCate();

        $searchKey = [
            'title'    => FormItem::make()->title(false)->placeholder('名称')->maxlength(30),
            'category' => FormItem::make('cascader')->title(false)->options($category)->placeholder('分类')->required(),
        ];
        // 设置表单
        $list = new PageList();
        // 表单字段
        $list->pageKey   = $keyList;
        $list->searchKey = $searchKey;
        $list->datas     = $data;

        return $list->send();
    }

    /**
     * 课程代理库--记录
     *
     * @return mixed
     */
    public function record()
    {
        $data = Request::post();
        $list = $this->agentLogic->getRecordList($data);

        return $this->parseToData($list, 1, '获取成功');
    }

    /**
     * 代理记录--详情
     *
     * @return mixed
     */
    public function info($id)
    {
        // 搜索功能
        $map[] = ['course_id', '=', $id];
        // 过期时间
        $termTime = Request::get('date/d', 0);
        if ($termTime > 0) {
            $termTime = Request::time() + ($termTime - 1) * 24 * 60 * 60;
            $map[]    = ['term_time', '<=', $termTime];
            $map[]    = ['term_time', '>', Request::time()];
        }

        $data = $this->agentLogic->getInfoList($map);
        // 定义字段
        $keyList = [
            'school'      => ListItem::make('custom')->title('代理机构')->width(140),
            // 'course_type_text' => ListItem::make()->title('课程类型')->width(40),
            'cost_price'  => ListItem::make('custom')->title('平台售价')->width(40),
            'price'       => ListItem::make('custom')->title('机构售价')->width(40),
            'onlinenum'   => ListItem::make()->title('线上订单')->width(40),
            'linenum'     => ListItem::make()->title('线下订单')->width(40),
            'ordernum'    => ListItem::make()->title('订单总量')->width(40),
            'order_price' => ListItem::make()->title('销售额')->width(40),
            'create_time' => ListItem::make()->title('代理时间')->width(40),
            'term_time'   => ListItem::make()->title('到期时间')->width(40)
        ];

        // 设置表单
        $list = new PageList();
        // 表单字段
        $list->pageKey = $keyList;
        $list->datas   = $data;

        return $list->send();
    }

    /**
     * 代理记录--详情--头部课程信息
     *
     * @return mixed
     */
    public function videoInfo()
    {
        $data = Request::post();
        $list = app(Course::class)->with(['cover_url'])->whereId($data['course_id'])->field('title,cover,price,scribing_price')->findOrEmpty();

        return $this->parseToData($list, 1, '获取成功');
    }

    /**
     * 代理记录--详情--搜索机构
     *
     * @param string $keyword
     * @return Response
     */
    public function searchSchool(string $keyword = ''): Response
    {
        $map  = [
            ['status', '=', 1],
            ['id', '<>', 1]
        ];
        $list = app(SchoolLogic::class)->getSearchList($keyword, 12, $map);

        return $this->parseToData($list, 1, '获取成功');
    }

    /**
     * 代理记录--详情--课程代理
     *
     * @return mixed
     */
    public function syncVideo()
    {
        $data                = Request::post();
        $course              = app(Course::class)->where('id', $data['vid'])->findOrFail();
        $data['course_type'] = $course->course_type;
        $data['price']       = $course->price;
        $video               = $this->agentLogic->syncVideo($data);

        return static::parseToData($video, 1, '代理成功');
    }

    /**
     * 代理记录--详情--删除代理课程
     *
     * @param $id
     * @return Response
     */
    public function delete($id): Response
    {
        $this->agentLogic->deleteAgent($id);

        return static::parseToData([], 1, '删除成功');

    }

    /**
     * 机构派发课程--获取课程列表
     *
     * @param int $id
     * @return mixed
     */
    public function getCourseList(int $id)
    {
        $mhmId = Request::get('mhm_id/d', request()->mhm_id);

        $map = [
            ['mhm_id', '=', $mhmId],
            ['solo', '=', 1]
        ];
        Request::has('title', 'get', true) && $map[] = ['title', 'like', '%' . Request::get('title/s') . '%'];
        $category = Request::get('category/d', 0);
        if ($category && $mhmId === 1) {
            $map[] = ['category', 'like', '%,' . $category . ',%'];
            $map[] = ['mhm_id', '=', $mhmId];
        } else if ($category) {
            $map[] = ['mhm_category', 'like', '%,' . $category . ',%'];
        }
        $count = Request::get('count/d', 15);
        $type  = Request::get('type/d', 1);
        $data  = [];

        switch ($type) {
            case 2:
                $mod = app(LiveLogic::class);
                break;
            case 3:
                $mod = app(LiveSmallLogic::class);
                break;
            case 4:
                $mod = app(ClassesLogic::class);
                break;
            case 1:
            default:
                $mod = app(VideoLogic::class);
                break;
        }

        $data = $mod->with(['cover_url'])
            ->where($map)
            ->where('id', 'not in', function ($query) use ($id) {
                $query->table(env('database.prefix') . 'course_agent')
                    ->where('mhm_id', $id)
                    ->where('term_time', '>', Request::time())
                    ->field('course_id');
            })
            ->field(['id', 'title', 'cover', 'scribing_price', 'price'])
            ->paginate($count);

        // 已选择数据
        // 已标记用户
        $course_ids   = $this->agentLogic->where('mhm_id', $id)->column('course_id');
        $checked_list = count($course_ids) > 0 ? app(Course::class)->where('id', 'IN', $course_ids)->field(['id' => 'value', 'title'])->select() : [];

        // 设置表单
        $list          = new PageList();
        $list->datas   = $data;
        $list->types   = [
            ['id' => 1, 'title' => '点播课'],
            ['id' => 2, 'title' => '大班课'],
            ['id' => 3, 'title' => '小班课'],
            ['id' => 4, 'title' => '班级课'],
        ];
        $list->checked = $checked_list;

        return $list->send();
    }

    /**
     * 机构派发课程--获取课程分类树形结构
     *
     * @return mixed
     */
    public function getCourseCategoryCascader()
    {
        $cates = app(Category::class)->cascader();

        return $this->parseToData($cates, 1, '获取成功');
    }

    /**
     * 机构派发课程--给机构添加课程
     *
     * @param int $id
     * @return mixed
     */
    public function addSchoolCourse(int $id)
    {
        $data = Request::post();

        $this->agentLogic->addSchoolCourse($id, $data);

        return $this->parseToData([], 1, '添加课程成功');
    }

    /**
     * 课程代理--机构
     *
     * @return mixed
     */
    public function school()
    {
        $mhmId = Request::get('mhm_id/d', request()->mhm_id);
        // 搜索功能
        $map = [];
        Request::has('title', 'get', true) && $map[] = ['c.title', 'like', '%' . Request::get('title/s') . '%'];
        $category = Request::get('category/d', 0);
        $category && $map[] = ['a.mhm_category', 'like', '%,' . $category . ',%'];
        // 获取当前机构代理的课程
        $data = $this->agentLogic->getAgentSchoolList($mhmId, $map);

        // 定义字段
        $keyList = [
            'title'            => ListItem::make('custom')->title('名称')->width(140),
            'course_type_text' => ListItem::make()->title('课程类型'),
            'cates'            => ListItem::make('custom')->title('分类')->width(142),
            'cost_price'       => ListItem::make()->title('平台售价'),
            'price'            => ListItem::make()->title('售价'),
            'is_recommend'     => ListItem::make('custom')->title('推荐课程')->width(40),
            'status'           => ListItem::make('custom')->title('上架状态')->width(40),
            'create_time'      => ListItem::make()->title('代理时间'),
            'term_time'        => ListItem::make()->title('到期时间')
        ];

        // 课程分类
        $category = app(Category::class)->cascaderCate();

        $searchKey = [
            'title'    => FormItem::make()->title(false)->placeholder('名称')->maxlength(30),
            'category' => FormItem::make('cascader')->title(false)->options($category)->placeholder('分类')->required(),
        ];
        // 设置表单
        $list = new PageList();
        // 表单字段
        $list->pageKey   = $keyList;
        $list->searchKey = $searchKey;
        $list->datas     = $data;

        return $list->send();
    }

    /**
     * 课程分销--机构--课程信息
     *
     * @return Response
     */
    public function getSchoolCourseInfo()
    {
        $post           = Request::post();
        $mhm_id         = request()->mhm_id;
        $data           = $this->agentLogic->getSchoolCourseInfo($mhm_id, $post);
        $data->mhmCates = app(Category::class)->cascaderCate();

        return $this->parseToData($data, 1, '获取成功');
    }

    /**
     * 课程分销--机构--课程信息保存
     *
     * @return mixed
     */
    public function schoolUpdate()
    {
        $data   = Request::post();
        $mhm_id = request()->mhm_id;
        $video  = $this->agentLogic->schoolUpdate($mhm_id, $data);

        return static::parseToData($video, 1, '编辑成功');
    }

    /**
     * 课程分销--机构--学员列表
     *
     * @param int $id
     * @return mixed
     */
    public function schoolUser(int $id)
    {
        // 搜索功能
        $map   = [];
        $mhmId = Request::get('mhm_id/d', request()->mhm_id);
        $map[] = ['mhm_id', '=', $mhmId];
        $data  = app(CourseStudent::class)->getList($id, $map, Request::get('phone/s', ''))->bindAttr('user', ['avatar_url', 'nick_name', 'phone'])->hidden(['user']);
        // 点播课和班级课显示学员学习情况
        // 定义字段
        $keyList = [
            'user'         => ListItem::make('custom')->title('用户'),
            'learn_rate'   => ListItem::make()->title('学习进度')->visible(),
            'total_time'   => ListItem::make()->title('累计学习时长')->visible(),
            'lately_time'  => ListItem::make()->title('最近学习时间')->visible(),
            'study_status' => ListItem::make('custom')->title('学习状态')->visible(),
            'from_text'    => ListItem::make()->title('加入方式'),
            'create_time'  => ListItem::make('custom')->title('加入时间'),
            'expire_time'  => ListItem::make()->title('过期时间')
        ];

        $searchKey = [
            'phone' => FormItem::make('input')->title(false)->placeholder('学员手机号')->maxlength(30),
        ];

        // 设置表单
        $list = new PageList();
        // 表单字段
        $list->pageKey   = $keyList;
        $list->searchKey = $searchKey;
        $list->datas     = $data;

        return $list->send();
    }

    /**
     * 课程代理库-学员-顶部统计
     *
     * @param int $id
     * @return mixed
     */
    public function schoolStatistic(int $id)
    {
        $mhm_id = request()->mhm_id;
        $data   = $this->agentLogic->getSchoolStatistic($id, $mhm_id);

        return $this->parseToData($data, 1, '获取成功');
    }

    /**
     * 编辑指定的字段
     *
     * @param $id
     * @param $field
     * @return Response
     */
    public function editField($id, $field): Response
    {
        $value = Request::put($field);
        $video = $this->agentLogic->editField($id, $field, $value);

        return static::parseToData($video, 1, '编辑成功');
    }

    /**
     * 课程代理库--机构--代理课程列表
     *
     * @param $id
     * @return mixed
     */
    public function getSchoolCourseInList($id)
    {
        // 搜索功能
        $map[] = ['mhm_id', '=', $id];

        $data = $this->agentLogic->getSchoolCourseInList($map);
        // 定义字段
        $keyList = [
            'course_title'     => ListItem::make('custom')->title('课程名称')->width(140),
            'course_type_text' => ListItem::make()->title('课程类型')->width(40),
            'cost_price'       => ListItem::make('custom')->title('平台售价')->width(40),
            'price'            => ListItem::make('custom')->title('机构售价')->width(40),
            'onlinenum'        => ListItem::make()->title('线上订单')->width(40),
            'linenum'          => ListItem::make()->title('线下订单')->width(40),
            'ordernum'         => ListItem::make()->title('订单总量')->width(40),
            'order_price'      => ListItem::make()->title('销售额')->width(40),
            'create_time'      => ListItem::make()->title('代理时间')->width(40),
            'term_time'        => ListItem::make()->title('到期时间')->width(40)
        ];

        // 设置表单
        $list = new PageList();
        // 表单字段
        $list->pageKey = $keyList;
        $list->datas   = $data;

        return $list->send();
    }
}
